//
//  JCCCollectViewController.swift
//  剂查查
//
//  Created by shoubin tao on 2024/12/1.
//  Copyright © 2024 shipin. All rights reserved.
//

import Foundation
import UIKit
import CommonTools



class JCCHistoryModel {
    var create_at: String = ""
    var gcode: String = ""
    var name:String = ""
    var score:Int = 0
    var grade:String = ""
    var data_image:String = ""
    var id:Int = 0
    var isSelect:Bool = false
    init(dict: [String: Any]) {
        self.create_at = dict["create_at"] as? String ?? ""
        self.gcode = dict["gcode"] as? String ?? ""
        self.name = dict["name"] as? String ?? ""
        self.score = dict["score"] as? Int ?? 0
        self.grade = dict["grade"] as? String ?? ""
        self.data_image = dict["data_image"] as? String ?? ""
        self.id = dict["id"] as? Int ?? 0
    }
    
    var gradeColor: UIColor? {
        jcc_gradeColor(grade: grade)
    }
}


class JCCHistoryTableViewCell: UITableViewCell {
    
    @IBOutlet weak var leftImageView: UIImageView!
    
    @IBOutlet weak var selectBtn: UIButton!
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var gradeLabel: UILabel!
    @IBOutlet weak var numberLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var containBtn: UIButton!
    
    var selectedCallback: () -> () = {}
    
    override func awakeFromNib() {
        super.awakeFromNib()
        leftImageView.layer.cornerRadius = 12
        bgView.layer.cornerRadius = 7
        containBtn.setTitle("含", for: .normal)
        containBtn.titleLabel?.font = 13.regular
        containBtn.cut(withRadius: 12.5)
        containBtn.isUserInteractionEnabled = false
        containBtn.setTitleColor(.white, for: .normal)
        contentView.backgroundColor = .blackf6
    }
    
    var  model: JCCHistoryModel = JCCHistoryModel(dict: [:])
//    var tableView:UITableView = UITableView()
    override func layoutSubviews() {
        
        
    }
}

class JCCHistoryViewController: BaseViewController {
    @IBOutlet weak var managerBtn: UIButton!
    @IBOutlet weak var selectCountLabel: UILabel!
    var isEdit: Bool = false
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var historyTableView: UITableView!
    @IBOutlet weak var deleteBtn: UIButton!
    
    var allSelectedBtn = NoHighlightedButton()
    @IBOutlet weak var bottomHeight: NSLayoutConstraint!
    var  models: [JCCHistoryModel] = []

    @IBAction func popAction(_ sender: Any) {
        self.popAction()
    }
    @IBAction func deleteAction(_ sender: Any) {
        EZLoadingActivity.show("正在删除...",disableUI: true)
        let deleteModel = models.filter { $0.isSelect }
        JCCNet.deleteHistory(ids: deleteModel.map{"\($0.id)"}) { (model, error) in
            self.isEdit = false
            self.updateUI()
            if(model?.isSuccess == true){
                EZLoadingActivity.hide()
                self.getData()
            }else {
                EZLoadingActivity.Settings.SuccessText = model?.info ?? ""
                EZLoadingActivity.hide(true, animated: false)
            }
        }
    }
    @IBAction func editAction(_ sender: Any) {
        self.isEdit = !self.isEdit
        self.updateUI()
        self.historyTableView.reloadData()
    }
    
    
    override func viewDidLoad() {
        setTitle("历史记录")
        bottomHeight.constant = 0
        view.backgroundColor = .white
        historyTableView.backgroundColor = .blackf6
        self.historyTableView.delegate = self
        self.historyTableView.dataSource = self
        self.historyTableView.separatorStyle = .none
        self.deleteBtn.layer.cornerRadius = 19
        getData()
        sutupAllSelectedBtn()
    }
    
    func sutupAllSelectedBtn() {
        allSelectedBtn = NoHighlightedButton(image: UIImage(named: "jcc_no_select")?.byResize(to: CGSize(width: 18, height: 18)), title: "全选", titleColor: .black3, font: 12.regular, in: bottomView, { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(18)
            make.width.equalTo(60)
            make.height.equalToSuperview()
        })
        allSelectedBtn.ty_imageTitleSpace = 5
        allSelectedBtn.setImage(UIImage(named: "jcc_select")?.byResize(to: CGSize(width: 18, height: 18)), for: .selected)
        allSelectedBtn.addBlock(for: .touchUpInside) {[unowned self] sender in
            guard let sender = sender as? UIButton else {
                return
            }
            sender.isSelected = !sender.isSelected
            for item in models {
                item.isSelect = sender.isSelected
            }
            historyTableView.reloadData()
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
//        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        self.navigationController?.navigationBar.isHidden = false
    }
    
    @IBAction func allSelectedAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:JCCHistoryTableViewCell = tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath) as! JCCHistoryTableViewCell
        let model:JCCHistoryModel = models[indexPath.row]
        cell.titleLabel.text = model.name
        cell.numberLabel.text = model.create_at
        
        cell.gradeLabel.text = "\(model.grade)级"
        cell.gradeLabel.textColor = model.gradeColor
        cell.containBtn.backgroundColor = cell.gradeLabel.textColor
        cell.selectBtn.setImage( UIImage.init(named:model.isSelect == true ? "jcc_select":"jcc_no_select" ), for: .normal)
        cell.selectBtn.isHidden = !self.isEdit
        if model.data_image.contains("&") {
            model.data_image = model.data_image.components(separatedBy: "&").first ?? ""
        }
        cell.leftImageView.sd_setImage(with: URL(string: model.data_image), placeholderImage: UIImage(named: ""))
        cell.model = model
        let isSelectCount = models.filter { $0.isSelect }.count
        selectCountLabel.text = "已选:\(isSelectCount)"
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if isEdit {
            let model:JCCHistoryModel = models[indexPath.row]
            model.isSelect = !model.isSelect
            tableView.reloadRow(at: indexPath, with: .none)
            let count = models.filter { $0.isSelect }.count
            allSelectedBtn.isSelected = count == models.count
        }
        else {
            
        }
    }
    
    func getData() {
        JCCNet.getHistoryList(completion: {
            model,error in
            let dicts = model?.result as! [Any]
            let models:[JCCHistoryModel] = dicts.map { JCCHistoryModel(dict: $0 as! [String : Any]) }
            self.models = models
            self.historyTableView.reloadData()
        })
       
    }
    func updateUI () {
        self.bottomView.isHidden = !self.isEdit
        self.managerBtn.setTitle(!self.isEdit ? "管理":"完成", for: .normal)
        if !isEdit {
            for item in models {
                item.isSelect = false
            }
        }
        bottomHeight.constant = isEdit ? 60 : 0
    }
}
